package com.eflying.user.service;

import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.http.HttpSession;

import com.eflying.common.utils.JavaMail;
import com.eflying.user.bean.User;
import com.eflying.user.dao.UserDao;
import com.eflying.user.exception.UserException;

import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;

/**
 * 用户业务层
 * @author 礼逊
 *
 */
public class UserService {
	private UserDao userDao = new UserDao();
	/**
	 * 修改密码功能
	 * @throws UserException 
	 */
	public void updatePassword(String uid,String oldPass,String newPass) throws UserException{
		try {
			if(!userDao.findByUidAndPwd(uid, oldPass)){
				throw new UserException("原密码错误!请重试!");
			}else{
				userDao.updatePassword(uid, newPass);
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		};
	}
	/**
	 * 登陆
	 */
	public User login(User user){
		try {
			return userDao.findByNameAndPass(user.getLoginname(), user.getLoginpass());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 校验用户名是否注册
	 * @param loginname
	 * @return
	 * @throws SQLException
	 */
	public boolean ajaxValidateLoginname(String loginname){
		try {
			return userDao.ajaxValidateLoginname(loginname);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 校验email是否注册
	 * @param loginname
	 * @return
	 * @throws SQLException
	 */
	public boolean ajaxValidateEmail(String email){
		try {
			return userDao.ajaxValidateEmail(email);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 用户注册
	 */
	public void regist(User user){
		/*
		 * 1.数据补齐
		 */
		user.setUid(CommonUtils.uuid());
		user.setStatus(false);
		user.setActivationCode(CommonUtils.uuid() + CommonUtils.uuid());
		/*
		 * 2.存入数据库
		 *
		 */
		try {
			userDao.add(user);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		/*
		 * 3.发送激活码邮件
		 */
		/*Properties prop = new Properties();
		try {
			prop.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		String host = prop.getProperty("host");
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");
		Session session = MailUtils.createSession(host, username, password);
		
		String from = prop.getProperty("from");
		String to = user.getEmail();
		String subject = prop.getProperty("subject");
		String content = MessageFormat.format(prop.getProperty("content"),user.getActivationCode());
		Mail mail = new Mail(from,to,subject,content);
		
		try {
			MailUtils.send(session, mail);
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}*/
		JavaMail jm = new JavaMail();
		try {
			jm.send(user);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 邮件激活过程
	 * 1.通过激活码得到对象
	 * >如果为null，说明激活码无效，抛出异常
	 * >如果status为true，抛出异常，已经激活，无需二次激活
	 * 2.修改用户status为true
	 * @throws UserException 
	 */
	public void checkActivationCode(String aCode) throws UserException{
		User user;
		try {
			user = userDao.checkActivationCode(aCode);
			if(user==null){
				throw new UserException("无效的激活码！");
			}else if(user.isStatus()){
				throw new UserException("您已经激活，无需再次激活！");
			}else{
				userDao.updateStatus(user.getUid(), true);
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 用户注册后台校验 (对各个字段逐个校验，生成一个map集合返回)
	 */
	public Map<String,String> validateRegist(User user,HttpSession httpSession){
		Map<String,String> errors = new HashMap<String,String>();
		/*
		 * 用户名校验
		 */
		String loginname = user.getLoginname();
		if(loginname.trim().isEmpty()||loginname == null){
			errors.put("loginname", "用户名不能为空！");
		}else if(loginname.length()<3 || loginname.length()>20){
			errors.put("loginname", "用户名长度必须3-20位");
		}else if(!this.ajaxValidateLoginname(loginname)){
			errors.put("loginname", "用户名已被注册！");
		}
		/*
		 * 注册密码校验
		 */
		String loginpass = user.getLoginpass();
		if(loginpass.trim().isEmpty()||loginpass == null){
			errors.put("loginpass", "密码不能为空！");
		}else if(loginname.length()<3 || loginname.length()>20){
			errors.put("loginpass", "密码长度必须3-20位");
		}
		/*
		 * 确认密码校验
		 */
		String reloginpass = user.getReloginpass();
		if(reloginpass.trim().isEmpty()||reloginpass == null){
			errors.put("reloginpass", "密码不能为空！");
		}else if(!reloginpass.equals(loginpass)){
			errors.put("reloginpass", "二次密码输入不一致！");
		}
		/*
		 * Email校验
		 */
		String email = user.getEmail();
		if(email.trim().isEmpty()||email == null){
			errors.put("email", "Email不能为空！");
		}else if(!email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")){
			errors.put("email", "Email格式不正确！");
		}else if(!this.ajaxValidateEmail(email)){
			errors.put("email", "Email已经存在！");
		}
		/*
		 * 验证码校验
		 */
		String verifyCode = user.getVerifyCode();
		String vCode = (String) httpSession.getAttribute("vCode");
		
		if(verifyCode.trim().isEmpty()||verifyCode == null){
			errors.put("verifyCode", "验证码不能为空！");
		}else if(!verifyCode.equalsIgnoreCase(vCode)){
			errors.put("verifyCode", "验证码不正确！");
		}
		
		return errors;
	}
	/**
	 * 登陆校验
	 * @param formUser
	 * @param session
	 * @return
	 */
	public Map<String, String> validateLogin(User formUser, HttpSession session) {
		Map<String,String> errors = new HashMap<String,String>();
		/*
		 * 用户名校验
		 */
		String loginname = formUser.getLoginname();
		if(loginname.trim().isEmpty()||loginname == null){
			errors.put("loginname", "用户名不能为空！");
		}else if(loginname.length()<3 || loginname.length()>20){
			errors.put("loginname", "用户名长度必须3-20位");
		}
		/*
		 * 注册密码校验
		 */
		String loginpass = formUser.getLoginpass();
		if(loginpass.trim().isEmpty()||loginpass == null){
			errors.put("loginpass", "密码不能为空！");
		}
		/*
		 * 验证码校验
		 */
		String verifyCode = formUser.getVerifyCode();
		String vCode = (String) session.getAttribute("vCode");
		
		if(verifyCode.trim().isEmpty()||verifyCode == null){
			errors.put("verifyCode", "验证码不能为空！");
		}else if(!verifyCode.equalsIgnoreCase(vCode)){
			errors.put("verifyCode", "验证码不正确！");
		}
		
		return errors;
	}
}
